
package com.ningmengs789.live.ui.fragment;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.ningmengs789.live.ActivityUtils;
import com.ningmengs789.live.GlideImageLoader;
import com.ningmengs789.live.R;
import com.ningmengs789.live.http.JsonBuilder;
import com.ningmengs789.live.http.OKHttpUtils;
import com.ningmengs789.live.Interface.RequestCallback;
import com.ningmengs789.live.live.live.common.widget.gift.utils.OnItemClickListener;
import com.ningmengs789.live.net.network.http.HttpException;
import com.ningmengs789.live.net.response.BannerResponse;
import com.ningmengs789.live.net.response.PopularUser1V1Response;
import com.ningmengs789.live.net.utils.json.JsonMananger;
import com.ningmengs789.live.ui.activity.LoginActivity;
import com.ningmengs789.live.ui.activity.MatchActivity;
import com.ningmengs789.live.ui.activity.ScreeningActivity;
import com.ningmengs789.live.ui.activity.TaskLobbyActivity;
import com.ningmengs789.live.ui.adapter.Hot1V1Adapter;
import com.ningmengs789.live.utils.CommonUtils;
import com.ningmengs789.live.utils.UserInfoUtil;
import com.youth.banner_lod.Banner;
import com.youth.banner_lod.BannerConfig;
import com.youth.banner_lod.listener.OnBannerListener;
import com.youth.banner_lod.transformer.AccordionTransformer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;


public class H_1_2_1v1_Fragment extends BaseFragment implements OnBannerListener, OnItemClickListener {

    private int page = 1;

    private List<PopularUser1V1Response.ListBean> mList = new ArrayList<>();

    @BindView(R.id.shimmer_recycler_view)
    RecyclerView shimmerRecycler;

    private View bannerView;
    private LinearLayout mContainerLL;

    private Hot1V1Adapter adapter;
    private GridLayoutManager mGridLayoutManager;

    private boolean isLoadingMore = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        mContext = getActivity();
        super.onCreate(savedInstanceState);
        if (bannerHeight == 0) {
            bannerHeight = ((getScreenWidth() - CommonUtils.dip2px(mContext, 12)) * 213) / 710;
        }
    }

    private int bannerHeight = 0;
    private int getScreenWidth() {
        return getResources().getDisplayMetrics().widthPixels;
    }

    @Override
    protected int setContentViewById() {
        return R.layout.fragment_h_2_1v1;
    }

    @Override
    protected void initAction() {
        bannerView = View.inflate(mContext.getApplicationContext(), R.layout.home_header_hot, null);
        mContainerLL = bannerView.findViewById(R.id.container_ll);

        mGridLayoutManager = new GridLayoutManager(mContext, 2);
        mGridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == 0 || mList.get(position - 1).getData_type() == 11){
                    return mGridLayoutManager.getSpanCount();
                }
                return 1;
            }
        });
        shimmerRecycler.setLayoutManager(mGridLayoutManager);
        adapter = new Hot1V1Adapter(mContext, getScreenWidth(), bannerView, this);
        shimmerRecycler.setAdapter(adapter);
    }

    private int info_complete;

    @Override
    public void onResume() {
        super.onResume();
        info_complete = UserInfoUtil.getInfoComplete();
    }

    private boolean isLogin(){
        boolean login;
        if (info_complete == 0) {
            startActivity(new Intent(getActivity(), LoginActivity.class));
            login = false;
        } else {
            login = true;
        }
        return login;
    }

    @Override
    public void onItemClick(Object bean, int position) {
        if (!isLogin()){
            return;
        }

        if (position < 1) {
            return;
        }
        position = position - 1;
        if (mList.get(position).getData_type() == 11){
            try {
                JSONObject content = new JSONObject(mList.get(position).getContent());
                String link = content.getString("link");
                if (!TextUtils.isEmpty(link)) {
                    Intent intent = new Intent("io.xchat.intent.action.webview");
                    intent.setPackage(getContext().getPackageName());
                    intent.putExtra("url", link);
                    startActivity(intent);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }else {
            try {
                JSONObject content = new JSONObject(mList.get(position).getContent());
                String user_id = content.getString("user_id");
                ActivityUtils.startUserHome(mContext, user_id);
                getActivity().overridePendingTransition(R.anim.slide_right_entry, R.anim.hold);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void initEvent() {
        shimmerRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int lastVisibleItem = mGridLayoutManager.findLastVisibleItemPosition();
                int totalItemCount = mGridLayoutManager.getItemCount();

                //表示剩下4个item自动加载，各位自由选择
                // dy>0 表示向下滑动
                if (lastVisibleItem >= totalItemCount - 4 && dy > 0) {
                    if (!isLoadingMore) {
                        isLoadingMore = true;
                        page++;
                        popularUser();                            }
                }
            }
        });

        bannerView.findViewById(R.id.home_header_hot_1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin()){
                    return;
                }
                startActivity(new Intent(mContext, TaskLobbyActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_right_entry, R.anim.hold);
            }
        });

        bannerView.findViewById(R.id.home_header_hot_2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin()){
                    return;
                }
                startActivity(new Intent(mContext, ScreeningActivity.class));
                getActivity().overridePendingTransition(R.anim.slide_right_entry, R.anim.hold);
            }
        });

        bannerView.findViewById(R.id.home_header_hot_3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin()){
                    return;
                }
                startActivity(new Intent(mContext, MatchActivity.class).putExtra("TYPE", 2));
                getActivity().overridePendingTransition(R.anim.slide_right_entry, R.anim.hold);
            }
        });

        bannerView.findViewById(R.id.home_header_hot_4).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!isLogin()){
                    return;
                }
                startActivity(new Intent(mContext, MatchActivity.class).putExtra("TYPE", 3));
                getActivity().overridePendingTransition(R.anim.slide_right_entry, R.anim.hold);
            }
        });
    }

    @Override
    protected void initData() {
        super.initData();
        showLoading();
        page = 1;
        popularUser();
        loadBanners();
        getTabList();
    }

    private BannerResponse mBanners;
    private void loadBanners(){
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("scene_id", 5)
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("app/ad/getBanner", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
            }
            @Override
            public void onSuccess(String result) {
                if (result != null) {
                    try {
                        mBanners = JsonMananger.jsonToBean(result, BannerResponse.class);
                        banner();
                    } catch (HttpException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void banner() {
        Banner mBanner = bannerView.findViewById(R.id.home_banner);
        try {
            if (mBanners.getList().size() > 0) {
                mBanner.setVisibility(View.VISIBLE);
                ViewGroup.LayoutParams params = mBanner.getLayoutParams();
                params.width = ViewGroup.LayoutParams.MATCH_PARENT;
                params.height = bannerHeight;
                mBanner.setLayoutParams(params);

                List<String> images = new ArrayList<>();
                for (int i = 0; i < mBanners.getList().size(); i++) {
                    images.add(CommonUtils.getUrl(mBanners.getList().get(i).getImg()));
                }

                mBanner.setImages(images)
//                .setBannerTitles(App.titles)//标题
                        .setBannerAnimation(AccordionTransformer.class)//动画
                        .setIndicatorGravity(BannerConfig.CENTER)//指示器位置
                        .setBannerStyle(BannerConfig.CIRCLE_INDICATOR)//指示器样式
                        .setDelayTime(3000)//延迟4S
                        .setImageLoader(new GlideImageLoader())
                        .setOnBannerListener(this)
                        .start();
            } else {
                mBanner.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            mBanner.setVisibility(View.GONE);
        }
    }

    @Override
    protected void updateViews(boolean isRefresh) {
        if (!isRefresh){
            showLoading();
        }

        page = 1;
        popularUser();
    }

    @Override
    public void OnBannerClick(int position) {
        String link = mBanners.getList().get(position).getLink();
        if (!TextUtils.isEmpty(link)) {
            Intent intent = new Intent("io.xchat.intent.action.webview");
            intent.setPackage(getContext().getPackageName());
            intent.putExtra("url", link);
            startActivity(intent);
        }
    }

    private void popularUser(){
        String body = "";
        try {
            body = new JsonBuilder()
                    .put("page", page)
                    .put("tab_id", tab_id)
                    .build();
        } catch (JSONException e) {
        }
        OKHttpUtils.getInstance().getRequest("onetone/index/popularUser", body, new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                hideLoading();
                if (page == 1) {
                    showNotData();
                }
            }
            @Override
            public void onSuccess(String result) {
                hideLoading();
                try {
                    PopularUser1V1Response response = JsonMananger.jsonToBean(result, PopularUser1V1Response.class);
                    isLoadingMore = false;
                    if (page == 1) {
                        if (mList.size() > 0) {
                            mList.clear();
                        }
                    }

                    mList.addAll(response.getList());
                    adapter.setCards(mList);

                    adapter.notifyDataSetChanged();

                    if (mList.size() == 0) {
                        showNotData();
                    }
                } catch (HttpException e) {
                    e.printStackTrace();
                    if (page == 1) {
                        showNotData();
                    }
                }
            }
        });
    }

    private void getTabList(){
        OKHttpUtils.getInstance().getRequest("onetone/index/getTabList", "", new RequestCallback() {
            @Override
            public void onError(int errCode, String errInfo) {
                mResult = null;
                typeContent();
            }
            @Override
            public void onSuccess(String result) {
                mResult = result;
                typeContent();
            }
        });
    }

    private String tab_id = "0";
    private String mResult;
    private void typeContent(){
        mContainerLL.setVisibility(View.VISIBLE);
        mContainerLL.removeAllViews();

        View view = LayoutInflater.from(mContext).inflate(R.layout.s_item, null);
        TextView tv = view.findViewById(R.id.s_item_id);
        tv.setText(getString(R.string.all_));
        tv.setTextColor(Color.parseColor("#ffffff"));
        tv.setBackgroundResource(R.drawable.s_bg2);
        mContainerLL.addView(view, 0);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateViewColor(0);
            }
        });

        try {
            if (mResult != null){
                JSONArray list = new JSONObject(mResult).getJSONArray("list");
                for (int i = 0; i < list.length(); i++) {
                    View view2 = LayoutInflater.from(mContext).inflate(R.layout.s_item, null);
                    TextView tv2 = view2.findViewById(R.id.s_item_id);
                    final int pos = i + 1;

                    tv2.setText(list.getJSONObject(i).getString("name"));
                    tv2.setTextColor(Color.parseColor("#333333"));
                    tv2.setBackgroundResource(R.drawable.s_bg);

                    mContainerLL.addView(view2, pos);

                    tv2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            updateViewColor(pos);
                        }
                    });
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void updateViewColor(int pos){
        for (int i = 0; i < mContainerLL.getChildCount(); i++) {
            LinearLayout ll = (LinearLayout) mContainerLL.getChildAt(i);
            TextView tv = (TextView) ll.getChildAt(0);
            String id = "0";
            if (i > 0){
                try {
                    id = new JSONObject(mResult).getJSONArray("list").getJSONObject(i - 1).getString("id");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            if (pos == i) {
                tab_id = id;
                tv.setTextColor(Color.parseColor("#ffffff"));
                tv.setBackgroundResource(R.drawable.s_bg2);
            }else{
                tv.setTextColor(Color.parseColor("#333333"));
                tv.setBackgroundResource(R.drawable.s_bg);
            }
        }

        page = 1;
        popularUser();
    }
}
